<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>系统参数设置</span>
          <div>
            <el-button type="primary" :icon="Plus" @click="handleAdd">新增参数</el-button>
            <el-button type="info" :icon="Setting" @click="groupDialog.visible = true">分组管理</el-button>
          </div>
            </div>
      </template>

      <el-tabs v-model="activeTab" type="border-card" @tab-click="handleTabClick">
        <el-tab-pane v-for="group in groupList" :key="group.id" :label="group.name" :name="String(group.id)">
          <!-- 搜索表单 -->
          <el-form :model="queryParams" ref="queryFormRef" :inline="true" class="search-form">
            <el-form-item label="参数名称" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入参数名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="参数键名" prop="key">
              <el-input v-model="queryParams.key" placeholder="请输入参数键名" clearable style="width: 240px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
              <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <!-- 操作按钮 -->
          <el-row :gutter="10" class="mb-3">
            <el-col :span="1.5">
              <el-button type="danger" :icon="Delete" :disabled="selectedIds.length === 0" @click="handleBatchDelete">批量删除</el-button>
            </el-col>
          </el-row>

          <!-- 表格 -->
          <el-table v-loading="loading" :data="settingList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="参数名称" prop="name" :show-overflow-tooltip="true" />
            <el-table-column label="参数键名" prop="key" :show-overflow-tooltip="true" />
            <el-table-column label="参数值" prop="value" :show-overflow-tooltip="true" />
            <el-table-column label="系统内置" align="center" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.isSystem ? 'danger' : 'info'">
                  {{ scope.row.isSystem ? '是' : '否' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createdAt" width="160">
              <template #default="scope">
                <span>{{ formatDateTime(scope.row.createdAt) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-button type="primary" link :icon="Edit" @click="handleUpdate(scope.row)">编辑</el-button>
                <el-button v-if="!scope.row.isSystem" type="danger" link :icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <pagination
            v-if="total > 0"
            :total="total"
            v-model:page="queryParams.page"
            v-model:limit="queryParams.limit"
            @pagination="getList"
          />
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加或修改参数对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="600px" append-to-body>
      <el-form ref="settingFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="参数分组" prop="groupId">
          <el-select v-model="form.groupId" placeholder="请选择参数分组">
            <el-option v-for="group in groupList" :key="group.id" :label="group.name" :value="group.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="参数名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入参数名称" />
        </el-form-item>
        <el-form-item label="参数键名" prop="key">
          <el-input v-model="form.key" placeholder="请输入参数键名" :disabled="form.id !== undefined && form.isSystem" />
        </el-form-item>
        <el-form-item label="参数值" prop="value">
          <el-input v-model="form.value" type="textarea" :rows="4" placeholder="请输入参数值" />
        </el-form-item>
        <el-form-item label="系统内置" v-if="form.id !== undefined">
          <el-switch v-model="form.isSystem" disabled />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="dialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 参数分组管理对话框 -->
    <el-dialog title="参数分组管理" v-model="groupDialog.visible" width="700px" append-to-body>
      <el-button type="primary" :icon="Plus" @click="handleAddGroup" class="mb-3">新增分组</el-button>
      
      <el-table :data="groupList" border>
        <el-table-column label="分组ID" prop="id" width="80" />
        <el-table-column label="分组名称" prop="name" />
        <el-table-column label="分组编码" prop="code" />
        <el-table-column label="排序" prop="sort" width="80" align="center" />
        <el-table-column label="创建时间" align="center" prop="createdAt" width="160">
          <template #default="scope">
            <span>{{ formatDateTime(scope.row.createdAt) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180">
          <template #default="scope">
            <el-button type="primary" link :icon="Edit" @click="handleUpdateGroup(scope.row)">编辑</el-button>
            <el-button type="danger" link :icon="Delete" @click="handleDeleteGroup(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加或修改分组对话框 -->
      <el-dialog
        :title="groupForm.id ? '编辑分组' : '新增分组'"
        v-model="groupFormDialog.visible"
        width="500px"
        append-to-body
      >
        <el-form ref="groupFormRef" :model="groupForm" :rules="groupRules" label-width="100px">
          <el-form-item label="分组名称" prop="name">
            <el-input v-model="groupForm.name" placeholder="请输入分组名称" />
          </el-form-item>
          <el-form-item label="分组编码" prop="code">
            <el-input v-model="groupForm.code" placeholder="请输入分组编码" />
          </el-form-item>
          <el-form-item label="显示排序" prop="sort">
            <el-input-number v-model="groupForm.sort" controls-position="right" :min="0" />
              </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitGroupForm">确 定</el-button>
            <el-button @click="groupFormDialog.visible = false">取 消</el-button>
          </div>
        </template>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { Search, Refresh, Plus, Delete, Edit, Setting } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getSettingList, 
  getSettingDetail, 
  createSetting, 
  updateSetting, 
  deleteSetting, 
  batchDeleteSettings,
  getSettingGroups,
  createSettingGroup,
  updateSettingGroup,
  deleteSettingGroup
} from '@/api/setting'
import Pagination from '@/components/Pagination/index.vue'

// 当前激活的选项卡
const activeTab = ref('1')

// 查询参数
const queryParams = reactive({
  page: 1,
  limit: 10,
  name: '',
  key: '',
  groupId: 1
})

// 表格数据
const settingList = ref([])
const groupList = ref([])
const loading = ref(false)
const total = ref(0)
const selectedIds = ref([])
const queryFormRef = ref(null)
const settingFormRef = ref(null)
const groupFormRef = ref(null)

// 弹窗对象
const dialog = reactive({
  title: '',
  visible: false
})

// 参数分组弹窗
const groupDialog = reactive({
  visible: false
})

// 参数分组表单弹窗
const groupFormDialog = reactive({
  visible: false
})

// 表单参数
const form = reactive({
  id: undefined,
  groupId: 1,
  name: '',
  key: '',
  value: '',
  isSystem: false,
  remark: ''
})

// 分组表单参数
const groupForm = reactive({
  id: undefined,
  name: '',
  code: '',
  sort: 0
})

// 表单验证规则
const rules = {
  groupId: [
    { required: true, message: '请选择参数分组', trigger: 'change' }
  ],
  name: [
    { required: true, message: '请输入参数名称', trigger: 'blur' }
  ],
  key: [
    { required: true, message: '请输入参数键名', trigger: 'blur' }
  ],
  value: [
    { required: true, message: '请输入参数值', trigger: 'blur' }
  ]
}

// 分组表单验证规则
const groupRules = {
  name: [
    { required: true, message: '请输入分组名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入分组编码', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入显示排序', trigger: 'blur' }
  ]
}

// 格式化日期时间
const formatDateTime = (value) => {
  if (!value) return ''
  return new Date(value).toLocaleString()
}

// 监听选项卡变化
watch(() => activeTab.value, (val) => {
  if (val) {
    queryParams.groupId = parseInt(val)
    getList()
  }
})

// 获取参数列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getSettingList(queryParams)
    settingList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取参数列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取分组列表
const getGroups = async () => {
  try {
    const res = await getSettingGroups()
    groupList.value = res.data
    if (groupList.value.length > 0 && !activeTab.value) {
      activeTab.value = String(groupList.value[0].id)
    }
  } catch (error) {
    console.error('获取参数分组失败:', error)
  }
}

// 选项卡点击事件
const handleTabClick = () => {
  queryParams.page = 1
  resetQuery()
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.page = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  queryParams.name = ''
  queryParams.key = ''
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 表单重置
const resetForm = (row) => {
  settingFormRef.value?.resetFields()
  Object.assign(form, {
    id: undefined,
    groupId: parseInt(activeTab.value) || 1,
    name: '',
    key: '',
    value: '',
    isSystem: false,
    remark: ''
  })
}

// 新增按钮操作
const handleAdd = () => {
  resetForm()
  dialog.visible = true
  dialog.title = '添加参数'
}

// 修改按钮操作
const handleUpdate = async (row) => {
  resetForm()
  dialog.visible = true
  dialog.title = '修改参数'
  loading.value = true
  try {
    const res = await getSettingDetail(row.id)
    Object.assign(form, res.data)
  } catch (error) {
    console.error('获取参数详情失败:', error)
  } finally {
    loading.value = false
  }
}

// 提交表单
const submitForm = () => {
  settingFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        if (form.id) {
          await updateSetting(form.id, form)
          ElMessage.success('修改成功')
        } else {
          await createSetting(form)
          ElMessage.success('新增成功')
        }
        dialog.visible = false
        getList()
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('提交失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 删除按钮操作
const handleDelete = (row) => {
  if (row.isSystem) {
    ElMessage.warning('系统内置参数不能删除')
    return
  }
  ElMessageBox.confirm(`确认删除参数"${row.name}"吗?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteSetting(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 批量删除操作
const handleBatchDelete = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }
  ElMessageBox.confirm('确认删除选中的参数吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await batchDeleteSettings(selectedIds.value)
      ElMessage.success('批量删除成功')
      getList()
    } catch (error) {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  })
}

// 新增分组按钮操作
const handleAddGroup = () => {
  groupFormRef.value?.resetFields()
  Object.assign(groupForm, {
    id: undefined,
    name: '',
    code: '',
    sort: 0
  })
  groupFormDialog.visible = true
}

// 修改分组按钮操作
const handleUpdateGroup = (row) => {
  groupFormRef.value?.resetFields()
  Object.assign(groupForm, { ...row })
  groupFormDialog.visible = true
}

// 提交分组表单
const submitGroupForm = () => {
  groupFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        if (groupForm.id) {
          await updateSettingGroup(groupForm.id, groupForm)
          ElMessage.success('修改成功')
        } else {
          await createSettingGroup(groupForm)
          ElMessage.success('新增成功')
        }
        groupFormDialog.visible = false
        await getGroups()
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('提交失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 删除分组按钮操作
const handleDeleteGroup = (row) => {
  ElMessageBox.confirm(`确认删除分组"${row.name}"吗?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteSettingGroup(row.id)
      ElMessage.success('删除成功')
      await getGroups()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

onMounted(() => {
  getGroups()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.mb-3 {
  margin-bottom: 15px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style> 